// WebSocketPlugin.js
import Vue from "vue";
import { getToken } from "@/utils/auth";

export default {
  install(Vue, options) {
    console.log(options, "options");
    // 创建WebSocket实例
    let ws = null;
    let heartbeatInterval = null
    const connect = () => {
      ws = new WebSocket(options.url);

      // 监听WebSocket的打开事件
      ws.onopen = () => {
        console.log("WebSocket连接已打开");
        // 定时发送心跳消息
        clearInterval(heartbeatInterval);
        heartbeatInterval = setInterval(() => {
          if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify({ 
              type: 0 ,
              authorization: getToken()
            }));
          }
        }, 10000);
      };

      // 监听WebSocket的消息事件
      ws.onmessage = (event) => {
        console.log("收到WebSocket消息:", event.data);
        // 你可以在这里将消息数据传递给Vue组件
        // 处理心跳响应
        if (event.data === '0') {
          console.log('Received heartbeat response');
        }
      };

      // 监听WebSocket的关闭事件
      ws.onclose = () => {
        console.log("WebSocket连接已关闭");
        clearInterval(heartbeatInterval);
        reconnect();
      };

      // 监听WebSocket的错误事件
      ws.onerror = (error) => {
        console.error("WebSocket发生错误:", error);
        clearInterval(heartbeatInterval);
        reconnect();
      };
    };
    connect();
    // 定义重连函数
    const reconnect = () => {
      if (ws.readyState === WebSocket.CLOSED) {
        console.log("正在尝试重新连接...");
        setTimeout(connect, 5000);
      }
    };
    // 在Vue的原型上添加$socket属性
    Vue.prototype.$socket = ws;
  },
};
